import { ADDRESS, CARTS, ORDERS } from "../../config";
import { observer } from "../../utils/observer";
import { time } from "../../utils/time.js";
import { Detail } from "../goods_detail/goods_detail";

let info;
let carts: Array<Detail> = [];
let allPrice = 0;
let allCount = 0;
let isChar = true;
let data = {
  info,
  allPrice,
  isChar,
  allCount,
  carts,
};
Page({
  data,
  onLoad(e) {
    data = observer(this.data, this);
    if (e.row) return this.single(e.row);
    this.init();
  },
  single(row: string) {
    data.info = (wx.getStorageSync(ADDRESS) || [])[0];
    const detial = JSON.parse(row) as Detail;
    data.allCount = 1;
    data.allPrice = detial.goods_price;
    data.carts = [detial];
  },
  init() {
    data.info = (wx.getStorageSync(ADDRESS) || [])[0];
    data.carts = (wx.getStorageSync(CARTS) as Array<Detail>).filter(
      (item) => item.flag
    );
    data.allPrice = data.carts.reduce((pre, item) => {
      return (pre += item.flag ? item.count * item.goods_price : 0);
    }, 0);
    data.allCount = data.carts.reduce((pre, item) => {
      return (pre += item.flag ? item.count : 0);
    }, 0);
  },
  pay() {
    if (!data.carts.length)
      return wx.showToast({
        title: "当前没有订单",
        icon: "error",
        duration: 1000,
      });
    wx.showLoading({ title: "支付中" });
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: "支付成功",
        icon: "success",
        duration: 1000,
      });
      setTimeout(() => {
        const order = {
          order_number:
            Math.random().toString(36).slice(2) +
            Math.random().toString(36).slice(2),
          total_price: this.data.allPrice,
          create_time: time("all"),
        };
        const orders = wx.getStorageSync(ORDERS) || [];
        orders.unshift(order);
        wx.setStorageSync(ORDERS, orders);
        if (data.isChar) {
          const carts = wx.getStorageSync(CARTS) as Array<Detail>;
          const nc = carts.filter((item) => !item.flag);
          wx.setStorageSync(CARTS, nc);
        }
        wx.redirectTo({
          url: "/pages/order/order",
        });
      }, 1000);
    }, 2000);
  },
});
